<?php

namespace app\m\controller;

use think\Db;

class We extends WeBase
{
    public function mp()
    {
        if ('POST' == $_SERVER['REQUEST_METHOD']) {

            loger(file_get_contents("php://input"), 'wx_mp');

            $msg = simplexml_load_string(file_get_contents("php://input"));
            if (!$msg)
                return;
            switch ($msg->MsgType->__toString()) {
                case 'text':
                    $this->dispathTextMsg($msg);
                    break;
                case 'event':
                    $this->EventMsg($msg);
                    break;
            }
        } elseif (isset($_GET['echostr'])) {
            $this->valid();
        }
    }

    private function EventMsg($msg)
    {
        $myNickname = $msg->ToUserName->__toString();
        $openid = $msg->FromUserName->__toString();
        // subscribe  unsubscribe    EventKey Ticket
        $event = $msg->Event->__toString();
        $now = $_SERVER['REQUEST_TIME'];
        if ('subscribe' == $event) {

            $user = $this->getUserInfo($openid);

            $eventKey = $msg->EventKey->__toString(); // qrscene_

            loger('subscribe.' . $eventKey, 'wx_event');

            //if ($user) {


            // 小程序 连接 slogen

            $qs = Db::query('select id from wx_mp where openid=? limit 0,1', [$openid]);
            if ($qs) {

                $id = $qs[0]['id'];
                // Db::execute('update wx_mp set ,subscribe=1 where id=' . $id); // 更新

                Db::table('wx_mp')->where('id', $id)->update($user);


            } else {
                $id = Db::table('wx_mp')->insertGetId($user);
            }
            // 记录行为


            // 记录关注行为
            Db::execute("insert into mp_trace set oid=$id,act=1,time=$now,spm=?", [$eventKey]);

            $str = "{$user['nickname']}你好，感谢关注 “河南校足办”  \r\n\r\n河南校园足球信息化平台";  // /:rose/:rose
            if ($eventKey) {
                // 记录并判断渠道
                $str .= "\r\n\r\n <a href=\"https://m.shinesports.cn/index\" data-miniprogram-appid=\"wx62408395b73989a9\" data-miniprogram-path=\"pages/index/index?id=123\">点击打开小程序</a>";
            }
            $this->responseText($myNickname, $openid, $now, $str);

            //}
        } else if ('CLICK' == $event) {

            $key = $msg->EventKey;
            if ($key == 'M_kf') {
                $this->responseText($myNickname, $openid, $now, '您好，客服桔子为您解答，有什么问题您请说。/微笑');
            } elseif ($key == 'M_help') {
                $this->responseText($myNickname, $openid, $now, '新手帮助，发送图文信息');
            }

        } elseif ('unsubscribe' == $event) {

            $qs = Db::query('select id from wx_mp where openid=? limit 0,1', [$openid]);
            if ($qs) {
                $id = $qs[0]['id'];
                // 记录不关注行为
                Db::execute("insert into mp_trace set oid=$id,act=3,time=$now");
                // 更新关注状态
                Db::execute('update wx_mp set subscribe=0 where id=' . $id);
            }
        } elseif ('SCAN' == $event) {
            $eventKey = $msg->EventKey->__toString();
            loger('SCAN.' . $eventKey, 'wx_event');

            $qs = Db::query('select id from wx_mp where openid=? limit 0,1', [$openid]);
            if ($qs) {
                $id = $qs[0]['id'];
                // 记录扫码行为
                Db::execute("insert into mp_trace set oid=$id,act=2,time=$now,spm=?", [$eventKey]);
            }

            // data-miniprogram-nickname="星座猫"

            // 发送小程序

            // $reply = '/:rose';

            $reply = "河南校足办信息化管理平台\r\n\r\n<a href=\"https://m.shinesports.cn/index\" data-miniprogram-appid=\"wx62408395b73989a9\" data-miniprogram-path=\"pages/index/index?id=123\">点击打开小程序</a>";


            $this->responseText($myNickname, $openid, $now, $reply);
        }
    }

    private function valid()
    {
        $echoStr = $_GET["echostr"];
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = $this->appToken;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if ($tmpStr == $signature) {
            echo $echoStr;
        }
    }

    private function dispathTextMsg($msg)
    {

        $time = $_SERVER['REQUEST_TIME'];
        $str = trim($msg->Content->__toString());
        if ($str == '直播') {

            // $reply = "HUBA2017河南大学生篮球联赛 \r\n\r\n<a href=\"" . config('wx_host') . "live/view_game\">在线直播入口</a> 点击进入";

            // $reply = '直播测试';


        } /*
        elseif ($str == '微信打印') {

            $reply = "转发打印照片 \r\n\r\n<a href=\"" . config('wx_host') . "we/we_print\">微信打印机</a>";

        } elseif ($str == '投票') {

            $reply = "投票入口 \r\n\r\n<a href=\"" . $this->get_vote_url() . "\">HUBA2017 MVP投票入口</a>";

        } */

        elseif ($str == '商城') {

            //$reply = '商城测试 :<a href="http://h5.g56.cn/shop">商城首页</a>';


        } else {

            $reply = '收到消息：' . $msg->Content . ' /微笑';

            // $reply = null;
        }

        if ($reply)
            $this->responseText($msg->ToUserName, $msg->FromUserName, $time, $reply);
    }


    /**
     * 设置公众号菜单
     */
    public function setMenu()
    {
        // return;

        // echo 'url:', $this->getAuthUrl(C('WX_HOST') . 'we/go?uc=ask');
        $service = array(
            array('type' => 'view', 'name' => '星盘.运势', 'url' => $this->getAuthUrl(config('wx_host') . 'we/go?uc=ask')),
            array('type' => 'view', 'name' => '我的', 'url' => $this->getAuthUrl(config('wx_host') . 'we/go?uc=my')),
            array('type' => 'click', 'name' => '在线客服', 'key' => 'M_kf'),
        );

        $menu = array(
            'button' => array(

                // array('type' => 'view', 'name' => '直播~点我', 'url' => config('wx_host') . 'we/huba2016?sf=wm'),
                // array('type' => 'view', 'name' => '投票', 'url' => $this->get_vote_url()),


                // array('type' => 'view', 'name' => '赛程 + 直播', 'url' => config('wx_host') . 'live/view'),
                // array('type' => 'view', 'name' => '投票', 'url' => config('wx_host') . 'yao/live_vote'),
                // array('type' => 'view', 'name' => '直播', 'url' => config('wx_host') . 'live/view_game'),
                // array('name' => '直播', 'sub_button' => [['type' => 'view', 'name' => '2017联赛', 'url' => config('wx_host') . 'live/view_game'], ['type' => 'view', 'name' => '华光杯3V3', 'url' => config('wx_host') . 'v3/play']]),
                // array('type' => 'view', 'name' => '五佳球', 'url' => config('wx_host') . 'live/view_highlights'),
                // array('type' => 'view', 'name' => 'MVP投票', 'url' => config('wx_host') . 'yao/huba2017_vote'),
                // array('name' => '直播', 'sub_button' => ['type' => 'view', 'name' => '2017联赛', 'url' => config('wx_host') . 'live/view_game']),
                // array('name' => '报名', 'sub_button' => ['type' => 'view', 'name' => '大学3V3','url' => config('wx_host') . '/v3/index']),
                // array('name' => '直播', 'sub_button' => [['type' => 'view', 'name' => '2017联赛', 'url' => config('wx_host') . 'live/view_game'], ['type' => 'view', 'name' => '大学3V3', 'url' => '']]),
                // array('type' => 'view', 'name' => '微信打印', 'url' => $this->getAuthUrl(config('wx_host') . 'we/we_print')),
                // array('name' => '客户服务', 'sub_button' => $service),

                // array('type' => 'miniprogram', 'name' => '团购', 'url' => 'https://a.g56.cn/', "appid" => 'wx62408395b73989a9', 'pagepath' => 'pages/index/index?f=1_0'),


                array('type' => 'miniprogram', 'name' => '考核', 'url' => 'https://m.shinesports.cn/index/mp', "appid" => 'wx62408395b73989a9', 'pagepath' => 'pages/index/index?f=1_0'),


                // array('type' => 'miniprogram', 'name' => '星缘', 'url' => 'https://a.g56.cn/', "appid" => 'wx631000a00b2326db', 'pagepath' => 'a/index/index?f=1_0'),

            )
        );
        $token = $this->getToken();
        if (!$token) {
            echo '获取token失败';
            return;
        }
        //echo 'token:', $token, '|';
        $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token=' . $token;
        $data = json_encode($menu, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        echo $data;
        $result = curl($url, 'post', $data);
        echo $result;
        return;
        $json = json_decode($result, true);
        if (!$json || $json['errcode'] != '0')
            echo '设置菜单失败,', $json['errmsg'], '<br />', $result;
        else
            echo '设置菜单成功';
    }


    public function qr_test()
    {
        // return;
        $token = $this->getToken();
        // $data = '{"expire_seconds": 2592000, "action_name": "QR_STR_SCENE", "action_info": {"scene": {"scene_str": "101_1256"}}}'; // 临时二维码

        $data = '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": 1}}}'; // 永久二维码

        $rev = curl('https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=' . $token, 'post', $data);
        $qr = json_decode($rev, true);
        $ticket = $qr['ticket'];
        $url = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . urlencode($ticket);
        echo $url;
    }

}
